package model

import (
	"fmt"
	"myserver/app/model/auth"
	"reflect"
)

var tables []interface{}

func CreateTable() {
	CreateSysFileTable()
	CreateUserTable()
	CreateSysGoodsTable()
	CreateUserShopTable()
	CreateClassificationTable()

	// 创建和跟新表
	err := db.AutoMigrate(tables...)
	if err != nil {
		fmt.Println(err.Error())
	}

}

func GETList[T any](page int, size int, key string, findKey string) ([]T, int64, error) {
	var (
		data  []T
		Count int64
		d     T
	)
	tx := db.Begin()
	list := tx
	cu := tx.Model(&data)
	if page > 0 {
		list = list.Offset((page - 1) * size).Limit(size)
	}
	name := reflect.TypeOf(d).Name()
	if name == "User" {
		list = list.Where("auth !=?", auth.Super_administrator)
		cu = cu.Where("auth !=?", auth.Super_administrator)
	}
	if findKey != "" {
		list = list.Where("is_del=? AND "+key+" LIKE ?", 0, "%"+findKey+"%")
		cu = cu.Where("is_del=? AND "+key+" LIKE ?", 0, "%"+findKey+"%")
	} else {
		list = list.Where("is_del=?", 0)
		cu = cu.Where("is_del=?", 0)
	}
	err := list.Order("update_time desc").Find(&data).Error

	if err != nil {
		return data, Count, err
	}
	err = cu.Count(&Count).Error
	if err != nil {
		return data, Count, err
	}
	return data, Count, nil
}
